// js操作封装
package redis

import (
	"context"
	"errors"
	"time"

	s "gitee.com/xiaoa7/jsetl/service"
	jsvmcore "gitee.com/xiaoa7/jsvm-core"
	"github.com/dop251/goja"
)

// 设置数据
func (r *Redis) Set(key, value string, timeout int64) error {
	stat := r.client.Set(context.TODO(), key, value, time.Duration(timeout)*time.Second)
	return stat.Err()
}

// 取得数据
func (r *Redis) Get(key string) (value string, err error) {
	stat := r.client.Get(context.TODO(), key)
	return stat.Result()
}

// 获取数据库实例
func getInstance(id string) (*Redis, error) {
	if ins := s.GetService(id); ins != nil {
		if _redis, ok := ins.(*Redis); ok {
			return _redis, nil
		}
	}
	return nil, errors.New("can't find redis instance")
}

func init() {
	//redis操作jsvm绑定
	jsvmcore.RegisterObject("redis", map[string]jsvmcore.HandleFn{
		"connect": func(vm *jsvmcore.JsVM) jsvmcore.JsVmFn {
			return func(params ...interface{}) goja.Value {
				if len(params) < 4 {
					return vm.State.ToValue("无效的输入参数,[redis实例,服务地址,密码,数据库索引]")
				}
				redisInstance, _ := params[0].(string)
				url, _ := params[1].(string)
				password := params[2].(string)
				index, _ := params[3].(string)
				if err := ConnectDB(redisInstance, url, password, index); err == nil {
					return vm.State.ToValue("")
				} else {
					return vm.State.ToValue(err.Error())
				}
			}
		},
		"set": func(vm *jsvmcore.JsVM) jsvmcore.JsVmFn {
			return func(params ...interface{}) goja.Value {
				if len(params) < 4 {
					return vm.State.ToValue("无效的输入参数,[redis实例,key,value,timeout]")
				}
				redisInstance, _ := params[0].(string)
				key, _ := params[1].(string)
				value := params[2].(string)
				timeout, _ := params[3].(int64)
				if _redis, err := getInstance(redisInstance); err == nil {
					_redis.Set(key, value, timeout)
				}
				return vm.State.ToValue("")
			}
		},
		"get": func(vm *jsvmcore.JsVM) jsvmcore.JsVmFn {
			return func(params ...interface{}) goja.Value {
				if len(params) < 2 {
					return vm.State.ToValue("无效的输入参数,[redis实例,key]")
				}
				redisInstance, _ := params[0].(string)
				key, _ := params[1].(string)
				if _redis, err := getInstance(redisInstance); err == nil {
					if result, err := _redis.Get(key); err == nil {
						return vm.State.ToValue(result)
					}
				}
				return vm.State.ToValue("")
			}
		},
	})
}
